package com.zcxy.edu.service.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.zcxy.common.config.RuoYiConfig;
import com.zcxy.common.core.domain.entity.SysRole;
import com.zcxy.common.core.domain.entity.SysUser;
import com.zcxy.common.utils.DateUtils;
import com.zcxy.common.utils.http.HttpUtilsNew;
import com.zcxy.edu.domain.EduStudent;
import com.zcxy.edu.domain.EduTeacherSmsConfig;
import com.zcxy.edu.domain.EduTeacherSmsLog;
import com.zcxy.edu.service.IEduTeacherSmsConfigService;
import com.zcxy.edu.service.IEduTeacherSmsLogService;
import com.zcxy.system.domain.SysConfig;
import com.zcxy.system.service.ISysConfigService;
import com.zcxy.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zcxy.edu.mapper.EduTeacherMapper;
import com.zcxy.edu.domain.EduTeacher;
import com.zcxy.edu.service.IEduTeacherService;

/**
 * 老师教职工Service业务层处理
 *
 * @author ruoyi
 * @date 2024-10-20
 */
@Service
public class EduTeacherServiceImpl implements IEduTeacherService
{
    @Autowired
    private EduTeacherMapper eduTeacherMapper;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private IEduTeacherSmsConfigService eduTeacherSmsConfigService;

    @Autowired
    private IEduTeacherSmsLogService eduTeacherSmsLogService;

    @Autowired
    private ISysUserService sysUserService;

    private static final Logger log = LoggerFactory.getLogger(EduStudentServiceImpl.class);

    /**
     * 查询老师教职工
     *
     * @param id 老师教职工主键
     * @return 老师教职工
     */
    @Override
    public EduTeacher selectEduTeacherById(Long id)
    {
        return eduTeacherMapper.selectEduTeacherById(id);
    }

    /**
     * 查询老师教职工列表
     *
     * @param eduTeacher 老师教职工
     * @return 老师教职工
     */
    @Override
    public List<EduTeacher> selectEduTeacherList(EduTeacher eduTeacher)
    {
        List<EduTeacher> list = eduTeacherMapper.selectEduTeacherList(eduTeacher);
        for(EduTeacher eduTeacher1 : list){
            SysUser sysUser = sysUserService.selectUserByUserName(eduTeacher1.getGH());
            eduTeacher1.setUserId(sysUser.getUserId());
        }
        return list;
    }

    /**
     * 新增老师教职工
     *
     * @param eduTeacher 老师教职工
     * @return 结果
     */
    @Override
    public int insertEduTeacher(EduTeacher eduTeacher)
    {
        EduTeacher edu = new EduTeacher();
        edu.setGH(eduTeacher.getGH());
        List<EduTeacher> eduTeacherList = eduTeacherMapper.selectEduTeacherList(edu);
        if(eduTeacherList.size() == 0){
            eduTeacher.setCreateTime(DateUtils.getNowDate());
            return eduTeacherMapper.insertEduTeacher(eduTeacher);
        }else{
            eduTeacher.setId(eduTeacherList.get(0).getId());
            eduTeacher.setUpdateTime(DateUtils.getNowDate());
            return eduTeacherMapper.updateEduTeacher(eduTeacher);
        }
    }

    /**
     * 修改老师教职工
     *
     * @param eduTeacher 老师教职工
     * @return 结果
     */
    @Override
    public int updateEduTeacher(EduTeacher eduTeacher)
    {
        eduTeacher.setUpdateTime(DateUtils.getNowDate());
        return eduTeacherMapper.updateEduTeacher(eduTeacher);
    }

    /**
     * 批量删除老师教职工
     *
     * @param ids 需要删除的老师教职工主键
     * @return 结果
     */
    @Override
    public int deleteEduTeacherByIds(Long[] ids)
    {
        return eduTeacherMapper.deleteEduTeacherByIds(ids);
    }

    /**
     * 删除老师教职工信息
     *
     * @param id 老师教职工主键
     * @return 结果
     */
    @Override
    public int deleteEduTeacherById(Long id)
    {
        return eduTeacherMapper.deleteEduTeacherById(id);
    }

    /**
     * 自动刷新数据
     */
    public void selectAndSaveApiData() throws UnsupportedEncodingException{
        String page = sysConfigService.selectConfigByKey("teacherDataPage");
        int pageNumber = Integer.parseInt(page);

        String url = RuoYiConfig.getTeacherPath();
        url += "?token="+sysConfigService.selectConfigByKey("eduToken");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id","2ff0e91090e611efbda3a8c17c606346");
        jsonObject.put("pageIndex", pageNumber);
        jsonObject.put("params",new JSONArray(new JSONObject()));

        String encodedUrl = URLEncoder.encode(jsonObject.toJSONString(), StandardCharsets.UTF_8.toString());
        url += "&jsonStr="+encodedUrl;

        log.info("请求获取老师信息地址参数:"+url);
        String result = HttpUtilsNew.sendGet(url,"","",null);
        log.info("请求获取老师信息结果"+result);

        JSONObject resultData = JSONObject.parseObject(result);
        if(resultData.getInteger("status") != 200){
            return;
        }

        JSONObject data = resultData.getJSONObject("data");

        if(data.getInteger("totalCount")==eduTeacherMapper.eduTeacherCount()){
            return;
        }else{
            pageNumber++;
        }

        //保存老师信息
        JSONArray jsonArray = data.getJSONArray("list");
        for(Object obj : jsonArray){
            JSONObject json = (JSONObject) obj;
            EduTeacher eduTeacher = JSON.toJavaObject(json, EduTeacher.class);
            insertEduTeacher(eduTeacher);

            //插入用户表
            SysUser sysUser = new SysUser();
            sysUser.setUserName(eduTeacher.getGH());
            sysUser.setNickName(eduTeacher.getXM());
            sysUser.setCreateBy("定时任务");
            sysUser.setDelFlag("0");
            sysUser.setRemark("教师");

            Long[] roleIds = new Long[] {100l};
            sysUser.setRoleIds(roleIds);
            sysUserService.saveCenterUser(sysUser);
        }

        SysConfig sysConfig = new SysConfig();
        sysConfig.setConfigKey("teacherDataPage");
        List<SysConfig> list = sysConfigService.selectConfigList(sysConfig);
        list.get(0).setConfigValue(pageNumber+"");
        sysConfigService.updateConfig(list.get(0));

    }

    /**
     * 发送当天生日的老师短信内容
     */
    public void sendTeacherSMS(){
        String data = DateUtils.dateTime();
//        String data = "1028";
        String poaToken = sysConfigService.selectConfigByKey("POAtoken");
        EduTeacherSmsConfig eduTeacherSmsConfig = eduTeacherSmsConfigService.selectEduTeacherSmsConfigByType("教师生日");

        EduTeacher eduTeacher = new EduTeacher();
        eduTeacher.setSFZJH(data);
//        eduTeacher.setXM("林庆新");
        List<EduTeacher> eduTeachers = eduTeacherMapper.selectEduTeacherBySFZJH(eduTeacher);
        //遍历当天生日的老师 发送短信
        for(EduTeacher eduT : eduTeachers){

            EduTeacherSmsLog eduTeacherSmsLogQuery = new EduTeacherSmsLog();
            eduTeacherSmsLogQuery.setTeacherId(eduT.getId());
            eduTeacherSmsLogQuery.setSendTime(data);
            eduTeacherSmsLogQuery.setStatus("1");
            List<EduTeacherSmsLog> logList = eduTeacherSmsLogService.selectEduTeacherSmsLogList(eduTeacherSmsLogQuery);
            if (logList.size()>0){
                continue;
            }

            String xM = eduT.getXM();
            String smsData = eduTeacherSmsConfig.getContent().replaceAll("teacherName",xM);
            String content = "{\n" +
                    "    \"appId\": \"308c705090e711ef2545c5e95440afdf\",\n" +
                    "    \"sendId\": \"\",\n" +
                    "    \"sendType\": [\n" +
                    "        \"SMS\"\n" +
                    "    ],\n" +
                    "    \"messageTypeCode\": \"MT1729651187000\",\n" +
                    "    \"promise\": false,\n" +
                    "    \"importantIdentity\": false,\n" +
                    "    \"toPersons\": \""+eduT.getGH()+"\",\n" +
                    "    \"data\": {\n" +
                    "        \"title\": \"生日祝福\",\n" +
                    "        \"paramValueJson\": {\n" +
                    "            \"content\": \""+smsData+"\"\n" +
                    "        }\n" +
                    "    }\n" +
                    "}";

            String url = RuoYiConfig.getPOAMsgPath();

            log.info("请求发送短信地址参数:"+url);
            log.info("请求发送短信地址参数:"+content);

            Map<String,String> heads = new HashMap<String,String>();
            heads.put("Authorization","Bearer "+poaToken);
            JSONObject result = HttpUtilsNew.sendPost(url,JSONObject.parseObject(content),heads);
            log.info("请求发送短信地址参数返回:"+result.toJSONString());

            EduTeacherSmsLog eduTeacherSmsLog = new EduTeacherSmsLog();
            eduTeacherSmsLog.setTeacherId(eduT.getId());
            eduTeacherSmsLog.setCreateTime(new Date());
            eduTeacherSmsLog.setContent(content);
            eduTeacherSmsLog.setSendTime(data);
            eduTeacherSmsLog.setResult(result.toJSONString());
            //发送成功 插入记录
            if(result.containsKey("code") && result.getInteger("code")==0){
                eduTeacherSmsLog.setStatus("1");
            }else{
                eduTeacherSmsLog.setStatus("2");
            }
            eduTeacherSmsLogService.insertEduTeacherSmsLog(eduTeacherSmsLog);
        }
    }

    /**
     * 重试发送失败的短信数据
     */
    public void reTryTeacherSMS(){
        String data = DateUtils.dateTime();
        String poaToken = sysConfigService.selectConfigByKey("POAtoken");

        EduTeacherSmsLog eduTeacherSmsLogQuery = new EduTeacherSmsLog();
        eduTeacherSmsLogQuery.setSendTime(data);
        eduTeacherSmsLogQuery.setStatus("2");
        List<EduTeacherSmsLog> logList = eduTeacherSmsLogService.selectEduTeacherSmsLogList(eduTeacherSmsLogQuery);
        for(EduTeacherSmsLog eduTeacherSmsLog : logList){
            String url = RuoYiConfig.getPOAMsgPath();
            String content = eduTeacherSmsLog.getContent();

            log.info("重试请求发送短信地址参数:"+url);
            log.info("重试请求发送短信地址参数:"+content);

            Map<String,String> heads = new HashMap<String,String>();
            heads.put("Authorization","Bearer "+poaToken);
            JSONObject result = HttpUtilsNew.sendPost(url,JSONObject.parseObject(content),heads);
            log.info("重试请求发送短信地址参数返回:"+result.toJSONString());

            eduTeacherSmsLog.setUpdateTime(new Date());
            eduTeacherSmsLog.setResult(result.toJSONString());
            //发送成功 插入记录
            if(result.containsKey("code") && result.getInteger("code")==0){
                eduTeacherSmsLog.setStatus("1");
            }else{
                eduTeacherSmsLog.setStatus("2");
            }
            eduTeacherSmsLogService.updateEduTeacherSmsLog(eduTeacherSmsLog);
        }
    }
}
